;
(function(factory) {
	layui.use(['layer', 'laypage', 'table', 'form','tree'], function() {
		factory(jQuery, window, document, layui);
	});
}(function($, window, document, layui) {
	$(function() {
		funOp.init();
		funOp.treeInit();
		funOp.tableOn();
	});

	var funOp = {
		limit: 10,
		roleId: '',
		init: function() {

			$('#seach_submit').click(function() {
				funOp.queryRole(1);
				return false;
			});

			$('#treeReset').click(function(){
				funOp.treeReset();
			});
			
			funOp.tableInit();
		},

		tableInit: function() {
			layui.table.render({
				elem: '#menu_table',
				toolbar: '#toolbarDemo',
				limit: funOp.limit,
				id: 'menu_table',
				cols: [
					[{
						fixed: 'left',
						title: '操作',
						width: 280,
						toolbar: '#barDemo'
					}, {
						field: 'id',
						title: 'ID',
						width: 50,
					}, {
						field: 'name',
						title: '角色名',
						width: 100
					}, {
						field: 'type',
						title: '角色类型',
						width: 100
					}, {
						field: 'createUser',
						title: '创建人',
						width: 100
					}, {
						field: 'createDate',
						title: '创建时间',
						width: 150
					}, {
						field: 'remark',
						title: '备注',
						width: 100
					}]
				],
				data: []
			});
		},

		getChildren: function(parentId, menuList) {
			var data = [];
			var treeObj;
			for(var i = 0;i <= menuList.length - 1;i++){
				if(parentId == menuList[i].parentId){
					treeObj = {
						id: menuList[i].id,
						title: menuList[i].name,
						children: funOp.getChildren(menuList[i].id, menuList)
					};
					data.push(treeObj);
				}
			}
			return data;
		},

		treeInit: function() {
			var s = 'select * from menu where del_flag = 0';
			var sParam = [];
			var cObj = {
				sql: $.fn.commUtil.getSqlStr(s, sParam)
			};
			$.newAjax({
				url: $.fn.commUtil.constant.baseUrl + '/dealSql',
				data: JSON.stringify(cObj),
				success: function(res) {
					if (res.code != 0) {
						return;
					}
					var menuList = res.data;
					var data = [];
					var treeObj;
					for(var i = 0;i <= menuList.length - 1;i++){
						if(menuList[i].level == 1){
							treeObj = {
								id: menuList[i].id,
								title: menuList[i].name,
								children: funOp.getChildren(menuList[i].id, menuList)
							};
							data.push(treeObj);
						}
					}

					layui.tree.render({
						elem: '#tree',  //绑定元素
						id: 'tree',
						showCheckbox: true,
						data: data
					});
				}
			});
		},

		tableOn: function() {
			//头工具栏事件
			layui.table.on('toolbar(menu_table)', function(obj){
				// var checkStatus = table.checkStatus(obj.config.id);
				switch(obj.event){
				case 'add':
					funOp.addRole();
				break;
				}
			});

			//监听行工具事件
			layui.table.on('tool(menu_table)', function(obj){
				var data = obj.data;
				if(obj.event === 'detail'){
					funOp.roleDeatil(obj.data);
				} else if(obj.event === 'del'){
					funOp.deleteRole(obj.data);
				} else if(obj.event === 'edit'){
					funOp.editRole(obj.data);
				} else if(obj.event === 'power'){
					funOp.rolePower(obj.data);
				}
			});
		},

		tableReload: function(pageIndex, total, data) {
			layui.table.reload('menu_table', {
				data: data
			});
			layui.laypage.render({
				elem: 'menu_page',
				limit: funOp.limit,
				curr: pageIndex,
				groups: 2,
				count: total,
				layout: ['count', 'prev', 'page', 'next'],
				jump: function(obj, first) {
					if (!first) {
						funOp.queryRole(obj.curr);
					}
				}
			});
		},

		queryRole: function(pageIndex) {
			var params = layui.form.val('seach_form');
			var where = ' where 0=0 ';
			var paramList = [];
			var pageParamList = [];
			$.each(params, function(key, value) {
				if(!value || value == ''){
					return true;
				}
				where += ' and ' + key + ' like concat("%", ? ,"%")';
				paramList.push(value);
			});
			where += ' and r.`del_flag` = 0';
			pageParamList = paramList.concat([(pageIndex - 1) * funOp.limit, (pageIndex) * funOp.limit]);
			
			var c = 'SELECT count(0) num from role r' + where;
			var s = 'SELECT u.username createUser,r.id,r.type,r.name,r.remark,r.create_date,r.del_flag delFlag'
			+' from role r left join user u on r.create_user = u.id ' + where + ' limit !,! ';
			
			var cObj = {
				sql: $.fn.commUtil.getSqlStr(c, paramList)
			};
			var sObj = {
				sql: $.fn.commUtil.getSqlStr(s, pageParamList)
			};
			$.newAjax({
				url: $.fn.commUtil.constant.baseUrl + '/dealSql',
				data: JSON.stringify(cObj),
				success: function(res) {
					// console.info(res)
					if (res.code != 0 || res.data.length == 0 || res.data[0] == 0) {
						alert(res.msg);
						return;
					}
					var total = res.data[0].num;
					$.newAjax({
						url: $.fn.commUtil.constant.baseUrl + '/dealSql',
						data: JSON.stringify(sObj),
						success: function(res) {
							// console.info(res)
							if (res.code != 0) {
								alert(res.msg);
								return;
							}
							funOp.tableReload(pageIndex, total, res.data);
						}
					});
				}
			});
		},

		roleDeatil: function(params, data) {
			layer.open({
				type: 1,
				title: '查看角色',
				area: ['600px','400px'],
				maxmin: true,
				content: $('#detailMsg')
			}); 
			//给表单赋值
			layui.form.val("detail", {
				"name": params.name,
				"type": params.type,
				"createUser": params.createUser,
				"createDate": params.createDate,
				"remark": params.remark
			});
		},

		addRole: function() {
			layer.open({
				type: 1,
				title: '新增角色',
				area: ['600px','400px'],
				maxmin: true,
				content: $('#addMsg')
			});
			//自定义验证规则
			// layui.form.verify({
			// 	name: function(value){
			// 	if(value.length < 5){
			// 		return '标题至少得5个字符啊';
			// 	}
			// 	}
			// });
			layui.form.on("submit(addSub)", function(data){
				// alert(JSON.stringify(data.field));				
				var a = 'select * from user where username = ? and del_flag = 0';
				var aParam = [];
				//获取登录人
				var loginUser = $.fn.commUtil.getLoginUser();
				var username = loginUser.username;
				aParam.push(username);

				var aObj = {
					sql: $.fn.commUtil.getSqlStr(a, aParam)
				};
				$.newAjax({
					url: $.fn.commUtil.constant.baseUrl + '/dealSql',
					data: JSON.stringify(aObj),
					success: function(res) {
						if (res.code != 0) {
							layer.msg('添加失败！');
							return;
						}
						var c = 'insert into role(`name`,type,remark,create_user,create_date,del_flag) values (?,?,?,?,?,0)';
						var cParam = [];

						var date = (new Date()).Format("yyyy-MM-dd hh:mm:ss");
						cParam.push(data.field.name);
						cParam.push(data.field.type);
						cParam.push(data.field.remark);
						cParam.push(res.data[0].id);
						cParam.push(date);

						var cObj = {
							sql: $.fn.commUtil.getSqlStr(c, cParam)
						};
						$.newAjax({
							url: $.fn.commUtil.constant.baseUrl + '/dealSql',
							data: JSON.stringify(cObj),
							success: function(res) {
								if (res.code != 0) {
									layer.msg('添加失败！');
									return;
								}
								layer.closeAll();
								funOp.queryRole(1);
								layer.msg(res.msg);
							}
						});
					}
				});
				return false;
			});
		},

		editRole: function(params, data) {
			//给表单赋值
			layui.form.val("edit", {
				"id": params.id,
				"name": params.name,
				"type": params.type,
				"createUser": params.createUser,
				"createDate": params.createDate,
				"remark": params.remark
			});
			// alert(JSON.stringify(params));
			layer.open({
				type: 1,
				title: '编辑角色',
				area: ['600px','400px'],
				maxmin: true,
				content: $('#editMsg')
			});
			layui.form.on("submit(editSub)", function(data){
				// alert(JSON.stringify(data.field));
				var s = 'update role set name = ?,type = ?,remark = ? where id = ?';
				var param = [];
				param.push(data.field.name);
				param.push(data.field.type);
				param.push(data.field.remark);
				param.push(data.field.id);
				var obj = {
					sql: $.fn.commUtil.getSqlStr(s, param)
				};
				$.newAjax({
					url: $.fn.commUtil.constant.baseUrl + '/dealSql',
					data: JSON.stringify(obj),
					success: function(res) {
						if (res.code != 0) {
							layer.msg('修改失败！');
							return;
						}
						// alert(JSON.stringify(res));
						layer.closeAll();
						funOp.queryRole(1);
						layer.msg(res.msg);
					}
				});
				return false;
			});
		},

		deleteRole: function(obj, data) {
			var id = obj.id;
			layer.confirm('确认删除吗？', function(index){
				// alert(JSON.stringify(obj));
				var c = 'update role set del_flag = 1 where id = ?';
				var param = [];
				param.push(id);
				var obj = {
					sql: $.fn.commUtil.getSqlStr(c, param)
				};
				$.newAjax({
					url: $.fn.commUtil.constant.baseUrl + '/dealSql',
					data: JSON.stringify(obj),
					success: function(res) {
						if (res.code != 0) {
							layer.msg('删除失败！');
							return;
						}
						funOp.queryRole(1);
						layer.msg(res.msg);
					}
				});
			});
		},

		treeReset: function() {
			layui.tree.reload('tree', {
				
			});
		},

		rolePower: function(obj, data) {
			funOp.treeReset();
			funOp.roleId = obj.id;
			var c = 'select rm.role_id,rm.menu_id,m.* from role_menu rm left join menu m on rm.menu_id = m.id where rm.role_id = ?';
			var param = [];
			param.push(obj.id);
			var obj = {
				sql: $.fn.commUtil.getSqlStr(c, param)
			};
			$.newAjax({
				url: $.fn.commUtil.constant.baseUrl + '/dealSql',
				data: JSON.stringify(obj),
				success: function(res) {
					if (res.code != 0) {
						return;
					}
					var idList = [];
					$.each(res.data, function (index, item) {
						if(item.hasNode == 0){
							idList.push(item.menuId);
						}
					});
					// alert(idList.length);
					if(idList.length != 0){
						layui.tree.setChecked('tree', idList); //批量勾选 id 为 2、3 的节点
					}
				}
			});

			layer.open({
				type: 1,
				title: '角色授权',
				area: ['600px','400px'],
				maxmin: true,
				content: $('#powerMsg')
			});

			layui.form.on("submit(treeSub)", function(obj,data){
				var checkedData = layui.tree.getChecked('tree');
				var list = [];
				var idList = funOp.getCheckedList(checkedData);
				if (idList != null && idList != ""){
					list = idList.split(",");
				}
				// alert(JSON.stringify(list));
				var roleId = funOp.roleId;
				var dSql = 'delete from role_menu where role_id = ?';
				var dParam = [];
				dParam.push(roleId);
				var sObj = {
					sql: $.fn.commUtil.getSqlStr(dSql, dParam)
				};
				$.newAjax({
					url: $.fn.commUtil.constant.baseUrl + '/dealSql',
					data: JSON.stringify(sObj),
					success: function(res) {
						if (res.code != 0) {
							layer.msg('授权失败！');
							return;
						}else{
							if(list.length > 0) {
								for (var i = 0;i < list.length;i++) {
									var aSql = 'insert into role_menu(role_id,menu_id) value(?,?)';
									var aParam = [];
									aParam.push(roleId);
									aParam.push(list[i]);
									var aObj = {
										sql: $.fn.commUtil.getSqlStr(aSql, aParam)
									};
									$.newAjax({
										url: $.fn.commUtil.constant.baseUrl + '/dealSql',
										data: JSON.stringify(aObj),
										success: function(res) {
											if (res.code != 0) {
												layer.msg('授权失败！');
												return;
											}else{
												layer.close(layer.index);
												layer.msg('授权成功！');
												// parent.reload();
											}
											
										}
									});
								}
							}else {
								layer.close(layer.index);
								layer.msg('授权成功！');
								return;
							}
						}
					}
				});
				return false;
			});
		},

		getCheckedList: function(data) {
			var id = "";
			$.each(data, function (index, item) {
				if (id != "") {
					id = id + "," + item.id;
				} else {
					id = item.id;
				}
				var i = funOp.getCheckedList(item.children);
				if (i != "") {
					id = id + "," + i;
				}
			});
			return id;
	  }
	};
}));
